const { workerData, parentPort } = require('worker_threads')
const fs = require('fs')
const readline = require('readline')

const { isPm2Hosting, logFilePath, start, end, oneWeekAgo, oneMonthAgo } = workerData

// 用于存储包下载量的对象
const downloadStats = {}
const oneWeekAgoPackageDownloads = {}
const oneMonthAgoPackageDownloads = {}

// 正则表达式匹配日志行
const log_Pattern = /requested 'GET \/([^']+)'/
const log_TimePattern = /\[(.*?)\] .* requested 'GET \/([^']+)'/

const log_PatternPm2 = /requested 'GET \/([^']+)'/
const log_TimePatternPm2 = /\[(.*?)\]http --- .* requested 'GET \/([^']+)'/

// 创建逐行读取日志的接口
const fileStream = fs.createReadStream(logFilePath, { start, end })
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity })

// 逐行读取日志
rl.on('line', (line) => {
  const logPattern = isPm2Hosting ? log_PatternPm2 : log_Pattern
  const logTimePattern = isPm2Hosting ? log_TimePatternPm2 : log_TimePattern

  const match = line.match(logPattern)
  if (match) {
    const packageName = decodeURIComponent(match[1])
    // 统计总数
    downloadStats[packageName] = (downloadStats[packageName] || 0) + 1
  }

  const matchTime = line.match(logTimePattern)
  if (matchTime) {
    const logTimeStr = matchTime[1]
    const packageName = decodeURIComponent(matchTime[2])

    // 解析日志时间
    const logTime = new Date(logTimeStr).getTime()

    // 如果日志时间在一周内，则统计下载量
    if (logTime >= oneWeekAgo) {
      oneWeekAgoPackageDownloads[packageName] = (oneWeekAgoPackageDownloads[packageName] || 0) + 1
    }

    // 如果日志时间在一个月内，则统计下载量
    if (logTime >= oneMonthAgo) {
      oneMonthAgoPackageDownloads[packageName] = (oneMonthAgoPackageDownloads[packageName] || 0) + 1
    }
  }
})

// 读取完成后返回结果
rl.on('close', () => {
  parentPort.postMessage({
    downloadStats,
    oneWeekAgoPackageDownloads,
    oneMonthAgoPackageDownloads
  })
})

rl.on('error', (error) => {
  parentPort.postMessage(null) // 返回空结果
})
